"use client";

import { useContext, useEffect, useRef, useState, useCallback } from "react";
import { MainContext } from "@/src/providers/MainProvider";
import KBKeySetting from "./Keyboard/KBKeySetting";
import KBLightSetting from "./Keyboard/KBLightSetting";
import KBSetting from "./Keyboard/KBSetting";
import KBDeviceInfo from "./Keyboard/KBDeviceInfo";
import Macro from "./Keyboard/Macro";
import Header from "./Common/Header";
import HomePage from "./Common/HomePage";
import { Box, Text, Flex, Image } from "@chakra-ui/react";
import { USBDetect } from "../shims/usb-detection";

// 定义组件内常量
const MAX_ZOOM_LEVEL = 1.5;

function MainKeyboard() {
  const {
    deviceStatus,
    setDeviceStatus,
    deviceOnline,
    setDeviceOnline,
    currentTab,
    connectKeyboard,
    t
  } = useContext(MainContext);

  // 使用useRef保存最新的设备状态，避免闭包问题
  const deviceStatusRef = useRef(deviceStatus);

  // 当deviceStatus改变时更新ref
  useEffect(() => {
    deviceStatusRef.current = deviceStatus;
  }, [deviceStatus]);

  // 设备断开连接的回调函数
  const handleDeviceRemove = useCallback((device: HIDDevice) => {
    console.log("设备已断开:", device.productName || "未知设备");
    setDeviceStatus(false);
    setDeviceOnline(false);
    // 添加1000毫秒延迟，确保设备初始化完成
    // setTimeout(() => {
    //   connectKeyboard([{ usagePage: 0xff00, usage: 0x0001 }]);
    // }, 1000);
  }, [connectKeyboard]);

  // 设备连接的回调函数
  const handleDeviceConnect = useCallback((device: HIDDevice) => {
    console.log("设备已连接:", device.productName || "未知设备");
    // if (device.vendorId === 0x088D && device.productId === 0x062E) {
    //   // 添加1000毫秒延迟，确保设备初始化完成
    //   setTimeout(() => {
    //     connectKeyboard([{ usagePage: 0xff00, usage: 0x0001 }]);
    //   }, 1000);
    // }
  }, [connectKeyboard]);

  // 阻止过度缩放的函数
  const preventExcessiveZoom = useCallback((e: WheelEvent) => {
    // 获取当前缩放级别
    const currentZoom = window.devicePixelRatio || 1;
    
    // 仅在按下Ctrl键且尝试放大并且当前缩放级别已达到或超过最大限制时阻止默认行为
    if (e.ctrlKey && e.deltaY < 0 && currentZoom >= MAX_ZOOM_LEVEL) {
      e.preventDefault();
    }
  }, []);

  // 阻止键盘缩放的函数
  const preventKeyboardZoom = useCallback((e: KeyboardEvent) => {
    const currentZoom = window.devicePixelRatio || 1;
    
    // 仅在按下Ctrl键且尝试放大并且当前缩放级别已达到或超过最大限制时阻止默认行为
    if ((e.ctrlKey || e.metaKey) && 
        (e.key === '+' || e.key === '=' || (e.key === 'ArrowUp' && e.ctrlKey)) && 
        currentZoom >= MAX_ZOOM_LEVEL) {
      e.preventDefault();
    }
  }, []);

  // 设置USB设备监控和缩放限制
  useEffect(() => {
    // 启动USB设备监控
    USBDetect.startMonitoring();
    
    // 添加USB设备事件监听器
    USBDetect.on("disconnect", handleDeviceRemove);
    USBDetect.on("connect", handleDeviceConnect);
    
    // 添加缩放限制事件监听器
    document.addEventListener('wheel', preventExcessiveZoom, { passive: false });
    document.addEventListener('keydown', preventKeyboardZoom);
    
    // 清理函数
    return () => {
      // 清理所有资源
      USBDetect.off("disconnect", handleDeviceRemove);
      USBDetect.off("connect", handleDeviceConnect);
      document.removeEventListener('wheel', preventExcessiveZoom);
      document.removeEventListener('keydown', preventKeyboardZoom);
      
      // 注意：不要在这里停止监控，因为其他组件可能仍需要监控
      // 如果确实需要停止，应在应用退出时调用 USBDetect.cleanup()
    };
  }, [handleDeviceRemove, handleDeviceConnect, preventExcessiveZoom, preventKeyboardZoom]);

  // 设置viewport限制
  useEffect(() => {
    // 查找或创建viewport meta标签
    const getOrCreateViewportMeta = () => {
      let meta = document.querySelector('meta[name="viewport"]') as HTMLMetaElement;
      if (!meta) {
        meta = document.createElement('meta');
        meta.name = 'viewport';
        document.head.appendChild(meta);
      }
      return meta;
    };
    
    const viewportMeta = getOrCreateViewportMeta();
    const originalContent = viewportMeta.content;
    
    // 设置限制最大缩放级别的视口设置
    viewportMeta.setAttribute('content', 
      `width=device-width, initial-scale=1.0, maximum-scale=${MAX_ZOOM_LEVEL}, user-scalable=yes`
    );
    
    // 组件卸载时恢复原始设置
    return () => {
      viewportMeta.setAttribute('content', originalContent);
    };
  }, []);

  // 根据设备状态渲染不同的内容
  return deviceStatus ? (
    <Box 
      style={{
        width: "100%",
        height: "100vh",
        position: "relative",
        overflow: "hidden",
        backgroundColor: "rgba(242, 243, 247, 0.1)"
      }}
    >
      {/* 背景区域 */}
      <Box
        position="absolute"
        top={0}
        left={0}
        w="100vw"
        h="100vh"
        overflow="hidden"
        bg="rgba(242, 243, 247, 0.1)"
        zIndex={0}
      >
        {/* 静态背景图 */}
        <Box position="relative" width="100%" height="100%">
          <Image
            src="./main_bkg.png"
            alt="背景图片"
            style={{
              width: '100%',
              height: '100%',
              objectFit: 'cover',
              position: 'absolute',
              top: 0,
              left: 0,
              opacity: 0.8,
              filter: 'brightness(0.8) contrast(1.1)',
            }}
            loading="eager"
          />
        </Box>
      </Box>

      {/* 主内容区 */}
      <Box 
        position="relative" 
        zIndex={1}
        display="flex"
        flexDirection="column"
        height="100vh"
      >
        {/* 标题栏区域 */}
        <Box
          position="sticky"
          top={0}
          zIndex={2}
        >
          <Header />
        </Box>

        {/* 主内容区 */}
        <Box 
          flex="1"
          p={2}
          overflowY="auto"
          overflowX="hidden"
          display="flex"
          justifyContent="center"
          sx={{
            '&::-webkit-scrollbar': { width: '3px' },
            '&::-webkit-scrollbar-track': { 
              width: '4px', 
              background: 'rgba(74, 222, 210, 0.1)',
              borderRadius: '24px'
            },
            '&::-webkit-scrollbar-thumb': { 
              background: 'rgba(74, 222, 210, 0.3)', 
              borderRadius: '24px',
              '&:hover': {
                background: 'rgba(74, 222, 210, 0.5)'
              }
            },
          }}
        >
          {/* 内容卡片容器 */}
          <Box
            w="full"
            bg="rgba(255, 255, 255, 0.05)"
            borderRadius="lg"
            p={1}
            boxShadow="0 4px 12px rgba(74, 222, 210, 0.1)"
            border="1px solid rgba(74, 222, 210, 0.1)"
            backdropFilter="blur(8px)"
            minH="calc(100vh - 16rem)"
            transition="all 0.3s ease"
            _hover={{
              boxShadow: "0 8px 24px rgba(74, 222, 210, 0.15)",
              borderColor: "rgba(74, 222, 210, 0.2)"
            }}
          >
            {
              {
                'kb-keyremap': <KBKeySetting />,
                'kb-light': <KBLightSetting />,
                'macro': <Macro />,
                'kb-setting': <KBSetting />,
                'kb-deviceinfo': <KBDeviceInfo />,
              }[currentTab]
            }
          </Box>
        </Box>
      </Box>

      {/* 设备离线遮罩层 */}
      {!deviceOnline && (
        <Flex
          position="absolute"
          top="0"
          left="0"
          width="100%"
          height="100%"
          bg="rgba(17, 24, 39, 0.7)"
          backdropFilter="blur(5px)"
          justifyContent="center"
          alignItems="center"
          zIndex="1000"
          userSelect="none"
          pointerEvents="none"
          sx={{
            animation: 'fadeIn 0.3s ease-in-out',
            '@keyframes fadeIn': {
              '0%': { opacity: 0 },
              '100%': { opacity: 1 }
            }
          }}
        >
          <Text
            color="white"
            fontSize="lg"
            bg="rgba(74, 222, 210, 0.1)"
            px="5"
            py="3"
            borderRadius="md"
            boxShadow="0 4px 12px rgba(74, 222, 210, 0.2)"
            border="1px solid rgba(74, 222, 210, 0.2)"
            sx={{
              animation: 'pulse 2s ease-in-out infinite',
              '@keyframes pulse': {
                '0%': { transform: 'scale(1)', boxShadow: '0 4px 12px rgba(74, 222, 210, 0.2)' },
                '50%': { transform: 'scale(1.02)', boxShadow: '0 4px 20px rgba(74, 222, 210, 0.3)' },
                '100%': { transform: 'scale(1)', boxShadow: '0 4px 12px rgba(74, 222, 210, 0.2)' }
              }
            }}
          >
            {t("70")}
          </Text>
        </Flex>
      )}
    </Box>
  ) : (
    <HomePage />
  );
}

export default MainKeyboard;
